const MongoClient = require('mongodb').MongoClient;

let ObjectId = require('mongodb').ObjectId;




let baseData = () => new Promise((resolve, reject) => {
    const client = new MongoClient('mongodb://localhost:27017', { useNewUrlParser: true });
    client.connect(function(err) {
        if (err) {
            reject(err)
        }
        resolve(client.db('student'));
    });
    client.close();
})

exports.findDB = async(tableName) => {
    let tmp = await baseData();
    let collection = tmp.collection(tableName);

    return new Promise((resolve, reject) => {
        collection.find({}).toArray(function(err, result) {
            if (err) {
                reject(err)
            }
            resolve(result)
        });
    })
}

exports.addDB = async(tableName, queryObj) => {
    let tmp = await baseData();
    let collection = tmp.collection(tableName);
    return new Promise((resolve, reject) => {
        collection.insertMany([queryObj], (err, result) => {
            if (err) {
                reject(err)
            }
            resolve(result)
        })
    })
}

exports.delDB = async(tableName, queryObj) => {
    console.log(queryObj)
    let tmp = await baseData();
    let collection = tmp.collection(tableName);
    return new Promise((resolve, reject) => {
        collection.deleteOne({ _id: ObjectId(queryObj.id) }, function(err, result) {
            if (err) {
                reject(err)
            }

            resolve(result)
        });
    })
}

exports.updateDB = async(tableName, queryObj) => {

    let tmp = await baseData();
    let collection = tmp.collection(tableName);

    return new Promise((resolve, reject) => {
        collection.updateMany({ _id: ObjectId(queryObj.id) }, { $set: { username: queryObj.username, age: queryObj.age, register: queryObj.register, telephone: queryObj.telephone, email: queryObj.email, enData: queryObj.enData } }, function(err, result) {
            if (err) {
                reject(err)
            }

            resolve(result)
        });
    })
}